package com.qdlc.p2p.biz.util;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.qdlc.p2p.common.util.NumberUtil;
import com.qdlc.p2p.common.util.SinaSignUtil;
import com.qdlc.p2p.common.util.SinaTools;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;

/**
 * 负责处理新浪通知请求的处理类
 * <p> 
 * 		负责对新浪返回的通知请求的封装，提供验签、返回响应、获取通知参数等功能。
 * </p>
 * @author linya 2015-12-30
 */
public class SinaNotifyRequestHandler {

	private static final String SIGN_MD5 = "MD5";
	
	private static final Logger log = Logger.getLogger(SinaNotifyRequestHandler.class);
	
	private String sign;				//签名
	
	private String signType;			//签名类型
	
	private String inputCharset;		//字符集
	
	private String signKey;				//签名Key
	
	private String linkParam;			//拼接签名参数字符串
	
	Map<String, String> notifyParam;	//获取的通知请求参数
	
	private SinaNotifyRequestHandler(String sign, String signType, String inputCharset){
		this.sign = sign;
		this.signType = signType;
		this.inputCharset = inputCharset;
	}
	
	public static SinaNotifyRequestHandler build(HttpServletRequest request){
		String sign = request.getParameter("sign");
		String signType = request.getParameter("sign_type");
		String inputCharset = request.getParameter("_input_charset");
		SinaNotifyRequestHandler notify = new SinaNotifyRequestHandler(sign, signType, inputCharset);
		notify.notifyParam = SinaTools.getParameterMap(request, true);
		notify.signKey = SIGN_MD5.equalsIgnoreCase(signType) ? SystemConfigHelper.getValue(Nid.GOODS_KEY) : SystemConfigHelper.getValue(Nid.CHECK_SIGN_KEY);
		notify.linkParam = SinaTools.createLinkString(notify.notifyParam, false);
		return notify;
	}
	
	/**
	 * 验签
	 * @return
	 */
	public boolean checkSign(){
		boolean checked = false;
		try {
			checked = SinaSignUtil.Check_sign(linkParam, sign, signType, signKey, inputCharset);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("++++ notify request check sign is failure.");
		}
		return checked;
	}
	
	/**
	 * 获取参数
	 * @param key
	 * @return
	 */
	public String getParam(String key){
		return notifyParam.get(key);
	}
	
	public int getIntParam(String key){
		return NumberUtil.getInt(notifyParam.get(key));
	}
	
	public double getDoubleParam(String key){
		return NumberUtil.getDouble2(notifyParam.get(key));
	}
	
	/**
	 * 写出验签的响应结果
	 * @param response
	 */
	public void writeResponse(HttpServletResponse response){
		try {
			boolean checked = checkSign();
			if (checked) {
				response.setContentType("text/html;charset=UTF-8");
				log.info("异步回调 success");
				response.getWriter().print("success");
			} else {
				response.setContentType("text/html;charset=UTF-8");
				log.info("异步回调 sign error!");
				response.getWriter().print("sign error!");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
